<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\msg\XhmsgNotice;
use Admin\Models\msg\XhmsgRecord;
use Helpers\Assets;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\UserPower;

class MsgController extends ControllerBase
{
    public function indexAction()
    {
        echo 'Msg';
    }


    private static $enums = [
        'iNoType' => [1 => '通知', 2 => '公告'],
    ];

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }

    /**
     * 当日未读通知公告
     *
     *
     *
     * create by zqk 20190219
     */
    public function todayMsgAction()
    {
        $time = date('Y-m-d');
        $userId = Main::getLoginUserInfo('userId');
        $builder = $this->modelsManager->createBuilder()
            ->columns("n.*")
            ->from(['n' => 'Admin\Models\msg\XhmsgNotice'])
            ->where("n.bDelete=0 AND n.tTime like '%{$time}%'");
        $builder->andWhere('( n.iNoType=1 AND n.sUserIds like :userId: ) OR n.iNoType=2', array('userId' => '%,' . $userId . ',%'));
        $builder->orderBy('n.tTime desc');
        $data = $builder->getQuery()->execute()->toArray();
        $enums = self::$enums;
        foreach ($data as $index => $row) {
            $record = XhmsgRecord::findFirst([
                'conditions' => 'iNoId=:iNoId: AND iUserId=:iUserId:',
                'bind' => ['iNoId' => $row['iNoId'], 'iUserId' => $userId],
            ]);
            if (!empty($record)) {
                unset($data[$index]);
                continue;
            }
            $data[$index]['iNoType'] = $enums['iNoType'][$row['iNoType']];
            $data[$index]['mContent'] = str_replace(array("\r\n", "\r", "\n"), '<br>', $data[$index]['mContent']);
            $data[$index]['mContent'] = str_replace(array(" ",), '&nbsp;', $data[$index]['mContent']);
            $data[$index]['mFooter'] = str_replace(array("\r\n", "\r", "\n"), '<br>', $data[$index]['mFooter']);
            $data[$index]['mFooter'] = str_replace(array(" ",), '&nbsp;', $data[$index]['mFooter']);
        }
        Main::runUserNameById($data, ['iCreateUserId' => 'iCreateUserId',
            'iLastModifyUserId' => 'iLastModifyUserId'], true);
        $this->view->pick('msg/todayMsg');
        Assets::importJs('js/msg/todayMsg.js');
        $this->view->setVars([
            'notices' => array_values($data),
        ]);
    }

    /**
     * 首页弹窗通知或者公告 设置为已读
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20190219
     */
    public function setMsgReadAction()
    {
        $iNoId = $this->request->get('iNoId');
        if (empty($iNoId)) {
            return $this->sendErrorResponse(400, '参数错误');
        }
        $userId = Main::getLoginUserInfo('userId');
        try {
            $obj = XhmsgRecord::findFirst([
                'conditions' => 'iNoId=:iNoId: AND iUserId=:iUserId:',
                'bind' => ['iNoId' => $iNoId, 'iUserId' => $userId],
            ]);
            if (!empty($obj)) {
                return $this->sendSuccessResponse('已读');
            }
            if (!$obj) {
                $obj = new XhmsgRecord();
            }
            $obj->iNoId = $iNoId;
            $obj->iUserId = $userId;
            $re = $obj->save();
            if ($re) {
                return $this->sendSuccessResponse('已读');
            } else {
                return $this->sendErrorResponse(500, '操作失败');
            }
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, $exception->getMessage());
        }
    }

    /**
     * notice主页
     * created by dale 2017/10/19
     */
    public function homeAction()
    {
        $userId = Main::getLoginUserInfo('userId');
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns("n.*")
                ->from(['n' => 'Admin\Models\msg\XhmsgNotice'])
                ->where('n.bDelete=0')->orderBy('n.tTime desc');
            $builder->limit(6);
            if (!UserPower::checkUserPower('Msg_NoAfList_All')) {  //具有全部查看权限
                $builder->andWhere('( n.iNoType=1 AND sUserIds like :userId: ) OR
                n.iNoType=2', array('userId' => '%,' . $userId . ',%'));
            };
            $notices = $builder->getQuery()->execute()->toArray();
            foreach ($notices as $index => $notice) {
                $notices[$index]['iNoType'] = self::$enums['iNoType'][$notice['iNoType']];
            }

            //今日通知或公告
            $time = date('Y-m-d');
            $builder = $this->modelsManager->createBuilder()
                ->columns("n.iNoId")
                ->from(['n' => 'Admin\Models\msg\XhmsgNotice'])
                ->where("n.bDelete=0 AND n.tTime like '%{$time}%'");
            $userId = Main::getLoginUserInfo('userId');
            $builder->andWhere('( n.iNoType=1 AND n.sUserIds like :userId: ) OR n.iNoType=2', array('userId' => '%,' . $userId . ',%'));
            $builder->orderBy('n.tTime desc');
            $data = $builder->getQuery()->execute()->toArray();
            foreach ($data as $k=> $v) {
                $record = XhmsgRecord::findFirst([
                    'conditions' => 'iNoId=:iNoId: AND iUserId=:iUserId:',
                    'bind' => ['iNoId' => $v['iNoId'], 'iUserId' => $userId],
                ]);
                if (!empty($record)) {
                    unset($data[$k]);
                    continue;
                }
            }
        } catch (\Exception $e) {
            die($e->getMessage());
        }
        $this->view->pick('msg/home');
        Assets::importJs('js/msg/myTool.js');
        Assets::importJs('js/msg/home.js');
        $this->view->setVars([
            'notices' => $notices,
            'num' => count($data),
        ]);
    }


    public function noticeDetailAction()
    {
        $iNoId = $this->request->getQuery('iNoId') or die('缺少参数');
        $this->view->pick('msg/noticeDetail');
        $notice = XhmsgNotice::findFirst([
            'conditions' => 'bDelete=0 AND iNoId=:iNoId:',
            'bind' => ['iNoId' => $iNoId],
        ])->toArray();
        $notice['iNoType'] = self::$enums['iNoType'][$notice['iNoType']];
        $notice['mContent'] = str_replace(array("\r\n", "\r", "\n"), '<br>', $notice['mContent']);
        $notice['mContent'] = str_replace(array(" ",), '&nbsp;', $notice['mContent']);
        $notice['mFooter'] = str_replace(array("\r\n", "\r", "\n"), '<br>', $notice['mFooter']);
        $notice['mFooter'] = str_replace(array(" ",), '&nbsp;', $notice['mFooter']);
        $this->saveRecord($iNoId);
        $this->view->setVars([
            'notice' => $notice,
        ]);
    }

    public function saveRecord($iNoId)
    {
        $userId = Main::getLoginUserInfo('userId');
        $obj = XhmsgRecord::findFirst([
            'conditions' => 'iNoId=:iNoId: AND iUserId=:iUserId:',
            'bind' => ['iNoId' => $iNoId, 'iUserId' => $userId],
        ]);
        if (!$obj) {
            $obj = new XhmsgRecord();
        }
        $obj->iNoId = $iNoId;
        $obj->iUserId = $userId;
        $obj->save();
    }


    /**
     * 通知公告列表
     * created by dale 2017/10/18
     */
    public function noticeListAction()
    {
        UserPower::checkUserPower('Msg_NoticeList') or die('缺少权限');
        Assets::easyUI();
        Assets::importJs('js/msg/noticeList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/msg/myTool.js');
        $this->view->pick('msg/noticeList');
        Template::exists('Msg_Notice', 'list') or die(Main::showMessageModal('Msg_Notice.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $listSearchArr = [];


        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 开始时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' 结束时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if (UserPower::checkUserPower('Msg_NoticeList_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Msg_NoticeList_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $this->view->setVars(array(
            'noticeList' => Template::createList('noticeList', 'Msg_Notice', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ));
    }


    public function getNoticeAction()
    {
        $this->view->disable();
        $key = $this->request->getPost('key', 'string');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime = $this->request->getPost('endTime', 'string');
        $builder = $this->modelsManager->createBuilder()
            ->columns("n.*")
            ->from(['n' => 'Admin\Models\msg\XhmsgNotice'])
            ->where('n.bDelete=0')->andWhere('n.iNoType=1')->orderBy('n.tTime desc');
        if (!UserPower::checkUserPower('Msg_NoAfList_All')) {  //具有全部查看权限
            $builder->andWhere('n.iCreateUserId = :iUserId:', array('iUserId' => Main::getLoginUserInfo('userId')));
        }
        if ($key) {
            $builder->andWhere('n.sTitle like :key:', array('key' => '%' . $key . '%'));
        }
        if ($startTime & $endTime) {
            $builder->andWhere('DATE_FORMAT(n.tTime,\'%Y-%m-%d\') >= :startTime:  AND DATE_FORMAT(n.tTime,\'%Y-%m-%d\') <= :endTime:', array('startTime' => $startTime, 'endTime' => $endTime));
        }


        $data = Main::runBuilderPaginator($builder, true);
        $enums = self::$enums;
        foreach ($data['rows'] as $index => $row) {
            $data['rows'][$index]['iNoType'] = $enums['iNoType'][$row['iNoType']];
            $data['rows'][$index]['seeInfo'] = '<div><a id="' . $row['iNoId'] . '" class="record">点击查看</a></div>';

        }
        Main::runUserNameById($data['rows'], ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'], true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 通知公告表单
     * created by dale 2017/10/18
     */
    public function noticeFormAction()
    {
        $iNoId = $this->request->getQuery('iNoId');
        if ($iNoId) {
            if (!UserPower::checkUserPower('Msg_NoticeList_Edit')) {
                $checkStr = "parent.$('#bt_modal_confirm').hide();";
            } else {
                $checkStr = '';
            }
        } else {
            $checkStr = '';
        }
        Assets::easyUI();
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/msg/myTool.js');
        Assets::importJs('js/msg/noticeForm.js');
        $this->view->pick('msg/noticeForm');
        if ($iNoId) {
            $notice = XhmsgNotice::findFirst([
                'conditions' => 'bDelete=0 AND iNoId=:iNoId:',
                'bind' => ['iNoId' => $iNoId],
            ])->toArray();
            $notice = json_encode($notice);
        } else {
            $notice = '1';
        }
        $userId = Main::getLoginUserInfo('userId');
        $depName = 'XX部';
        if (Main::getLoginUserInfo('logonName') != 'admin') {
            $staff = XhhrmStaff::findFirst([
                'columns' => 'sDepIds',
                'conditions' => 'iUserId = :iUserId: AND bDelete = 0',
                'bind' => ['iUserId' => $userId],
            ]);
            if ($staff) {
                $depIds = $staff->sDepIds;
                $depId = end(array_values(array_filter(explode(',', $depIds))));
                $depName = XhhrmDepart::getDepEnum()[$depId];
            }

        }

        $this->view->setVars([
            'notice' => $notice,
            'iNoType' => self::$enums['iNoType'],
            'check' => $checkStr,
            'dateTime' => date('Y年m月d日', time()),
            'depName' => $depName,
        ]);
    }


    /**
     * 新增通知
     *
     * created by dale 2017/10/18
     */
    public function saveNoticeAction()
    {
        $this->view->disable();
        $iNoId = $this->request->getPost('iNoId', 'string');
        if ($iNoId) {
            UserPower::checkUserPower('Msg_NoticeList_Edit') or die('没有权限');
            $obj = XhmsgNotice::findFirst([
                'conditions' => 'bDelete=0 AND iNoId=:iNoId:',
                'bind' => ['iNoId' => $iNoId],
            ]);
        } else {
            UserPower::checkUserPower('Msg_NoticeList_Add') or die('没有权限');
            $obj = new XhmsgNotice();
            $obj->tTime = date('Y-m-d H:i:s', time());
        }
        $obj->assign($this->request->getPost());
        $sNoticeIds = $this->request->getPost('sNoticeIds');
        $newArray = [];
        $sNoticeIds = array_filter(explode(',', $sNoticeIds));
        foreach ($sNoticeIds as $sNoticeId) {
            if (is_bool(strpos($sNoticeId, 'D-'))) {
                $newArray[] = $sNoticeId;
            }
        }
        if ($obj->iNoType == 1) {
            $obj->sUserIds = ',' . implode(',', $newArray) . ',';
        }
        if ($obj->save()) {
            try {
                if ($obj->bMessage == 1) {
                    $this->sendMsg($obj->iNoId, $obj->sTitle, $obj->sUserIds);
                }
            } catch (\Exception $e) {
                return $this->sendErrorResponse(500, $e->getMessage());
            }

            if ($iNoId) {
                return $this->sendSuccessResponse('编辑成功');
            } else {
                return $this->sendSuccessResponse('新增成功');
            }

        } else {
            return $this->sendSuccessResponse('新增失败');
        }
    }

    /**
     * 发送短信
     *
     * create by dale 20171226
     */
    public function sendMsg($id, $title, $userIds)
    {
        $url = Tool::buildUrl('frontend/msg/noticeDetail', ['iNoId' => $id]);
        $msg = '你有新的通知：' . $title . ',点击此处查看：' . $url;
        $ids = array_values(array_filter(explode(',', $userIds)));
        $phones = XhhrmStaff::find([
            'columns' => 'sSelfPhone',
            'conditions' => 'bDelete = 0 and iUserId in ({ids:array}) ',
            'bind' => ['ids' => $ids],
        ])->toArray();
        $phones = array_values(array_filter(array_column($phones, 'sSelfPhone')));
        if (count($phones) > 0) {
            $flag = true;
            foreach ($phones as $phone) {
                if (!$this->sendMsgToPhone($phone, $msg)) {
                    $flag = false;
                }
            }
            if (!$flag) {
                throw new \Exception('发送失败');
            }
        } else {
            throw new \Exception('没有需要发送的号码');
        }
    }

    /**
     * 发送短信
     *
     * @param $phoneNum
     * @param $msg
     * @return bool
     *
     * create by dale 20171226
     * modify by ck 20180629
     */
    public function sendMsgToPhone($phoneNum, $msg)
    {
        return Main::sendSMS($phoneNum, $msg);
//        $data = [
//            'appId'	=> 'platform',
//            'clientId'	=> $phoneNum,
//            'payload'	=> $msg,
//            'type'		=> 'SMS'
//        ];
//        $http = new HttpClient();
//        $url  = Main::getConfigByName('bpm')['msgUrl'];
//        $response = $http->postJson($url, $data);
//        if(!$response->isSuccess()) return false;
//        $body = $response->toArray();
//        return $body['code'] == 'OK' ? true : false;
    }


    /**
     * 删除通知公告
     * created by dale 2017/10/18
     */
    public function delNoticeAction()
    {
        UserPower::checkUserPower('Msg_NoticeList_Del') or die('没有权限');
        $ids = $this->request->getPost('ids', 'string') or die('缺少参数');
        $ids = explode(',', $ids);
        $res = XhmsgNotice::deleteRecord('iNoId', $ids);
        if ($res) {
            return $this->sendSuccessResponse('删除成功');
        } else {
            return $this->sendSuccessResponse('删除失败');
        }
    }

    /**
     * 通知公告查看进度
     * created by dale 2017/10/18
     */
    public function noticeProcessAction()
    {
        $id = $this->request->getQuery('id', 'string') or die('缺少参数');
        $this->view->pick('msg/noticeProcess');
        try {
            $notice = XhmsgNotice::findFirst([
                'conditions' => 'bDelete=0 AND iNoId=:iNoId:',
                'bind' => ['iNoId' => $id],
            ])->toArray();
            if ($notice['iNoType'] == 2) {//公告
                $staffs = XhhrmStaff::find([
                    'columns' => 'iStaffId,iUserId,sStaffName,sDepIds',
                    'conditions' => 'bDelete=0 AND iUserId is not null AND iStaffStatus=1',
                ])->toArray();  //所有人
                $userIds = array_values(array_filter(array_column($staffs, 'iUserId')));
                $totalC = count($userIds);
                $rec = XhmsgRecord::find([
                    'conditions' => 'bDelete=0 AND iNoId=:iNoId: AND iUserId in ({ids:array})',
                    'bind' => ['iNoId' => $id, 'ids' => $userIds],
                ])->toArray();
                $userArray = array_column($staffs, null, 'iUserId');
                if ($rec == []) {
                    $nowC = 0;
                } else {
                    $nowC = count($rec);
                    foreach ($rec as $index => $value) {
                        unset($userArray[$value['iUserId']]);
                    }

                }

            } else {//通知
                $userIds = array_values(array_filter(explode(',', $notice['sUserIds'])));
                $totalC = count($userIds); //总数
                $rec = XhmsgRecord::find([
                    'conditions' => 'bDelete=0 AND iNoId=:iNoId: AND iUserId in ({ids:array})',
                    'bind' => ['iNoId' => $id, 'ids' => $userIds],
                ])->toArray();

                $staffs = XhhrmStaff::find([
                    'columns' => 'iStaffId,iUserId,sStaffName,sDepIds',
                    'conditions' => 'bDelete=0 AND iUserId in ({ids:array})',
                    'bind' => ['ids' => $userIds],
                ])->toArray();   //所有需要通知的人
                $userArray = array_column($staffs, null, 'iUserId');
                if ($rec == []) {
                    $nowC = 0;
                } else {
                    $nowC = count($rec);
                    foreach ($rec as $index => $value) {
                        unset($userArray[$value['iUserId']]);
                    }

                }
            }

            $userArray = array_values($userArray);
            foreach ($userArray as $index => $value) {
                $userArray[$index]['sDepIds'] = \Admin\Models\hrm\XhhrmDepart::getDepName($value['sDepIds']);
            }
            $this->view->setVars([
                'process' => intval($nowC / $totalC * 100) . '%',
                'processStr' => $nowC . '/' . $totalC,
                'userArray' => $userArray,
            ]);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * 公告列表
     * created by dale 2017/10/19
     */
    public function afficheListAction()
    {
        UserPower::checkUserPower('Msg_AfficheList') or die('没有权限');
        Assets::easyUI();
        Assets::importJs('js/msg/afficheList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/msg/myTool.js');
        $this->view->pick('msg/afficheList');
        Template::exists('Msg_Affiche', 'list') or
        die(Main::showMessageModal('Msg_Affiche.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $listSearchArr = [];
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 开始时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' 结束时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search',
            'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if (UserPower::checkUserPower('Msg_AfficheList_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Msg_AfficheList_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $this->view->setVars(array(
            'afficheList' => Template::createList('afficheList', 'Msg_Affiche', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ));
    }

    /**
     * 公告数据
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017/10/19
     */
    public function getAfficheAction()
    {
        $this->view->disable();
        UserPower::checkUserPower('Msg_AfficheList') or die('没有权限');
        $key = $this->request->getPost('key', 'string');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime = $this->request->getPost('endTime', 'string');
        $builder = $this->modelsManager->createBuilder()
            ->columns("n.*")
            ->from(['n' => 'Admin\Models\msg\XhmsgNotice'])
            ->where('n.bDelete=0 AND n.iNoType=2')->orderBy('n.tTime desc');

        if (!UserPower::checkUserPower('Msg_NoAfList_All')) {  //具有全部查看权限
            $builder->andWhere('n.iCreateUserId = :iUserId:', array('iUserId' => Main::getLoginUserInfo('userId')));
        }
        if ($key) {
            $builder->andWhere('n.sTitle like :key:', array('key' => '%' . $key . '%'));
        }
        if ($startTime & $endTime) {
            $builder->andWhere('DATE_FORMAT(n.tTime,\'%Y-%m-%d\') >= :startTime:  AND DATE_FORMAT(n.tTime,\'%Y-%m-%d\') <= :endTime:', array('startTime' => $startTime, 'endTime' => $endTime));
        }

        $data = Main::runBuilderPaginator($builder, true);
        $enums = self::$enums;
        foreach ($data['rows'] as $index => $row) {
            $data['rows'][$index]['iNoType'] = $enums['iNoType'][$row['iNoType']];
            $data['rows'][$index]['seeInfo'] = '<div><a id="' . $row['iNoId'] . '" class="record">点击查看</a></div>';
        }
        Main::runUserNameById($data['rows'], ['iCreateUserId' => 'iCreateUserId',
            'iLastModifyUserId' => 'iLastModifyUserId'], true);
        return $this->sendJsonResponse($data);
    }

    /**
     * 公告表单
     *
     * created by dale 2017/10/19
     */
    public function afficheFormAction()
    {
        $iNoId = $this->request->getQuery('iNoId');
        if ($iNoId) {
            if (!UserPower::checkUserPower('Msg_AfficheList_Edit')) {
                $checkStr = "parent.$('#bt_modal_confirm').hide();";
            } else {
                $checkStr = "";
            }
        } else {
            $checkStr = '';
        }
        Assets::easyUI();
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/msg/myTool.js');
        Assets::importJs('js/msg/afficheForm.js');
        $this->view->pick('msg/afficheForm');
        if ($iNoId) {
            $notice = XhmsgNotice::findFirst([
                'conditions' => 'bDelete=0 AND iNoId=:iNoId:',
                'bind' => ['iNoId' => $iNoId],
            ])->toArray();
            $notice = json_encode($notice);
        } else {
            $notice = '1';
        }
        $userId = Main::getLoginUserInfo('userId');
        $depName = 'XX部';
        if (Main::getLoginUserInfo('logonName') != 'admin') {
            $staff = XhhrmStaff::findFirst([
                'columns' => 'sDepIds',
                'conditions' => 'iUserId = :iUserId: AND bDelete = 0',
                'bind' => ['iUserId' => $userId],
            ]);
            if ($staff) {
                $depIds = $staff->sDepIds;
                $depId = end(array_values(array_filter(explode(',', $depIds))));
                $depName = XhhrmDepart::getDepEnum()[$depId];
            }

        }

        $this->view->setVars([
            'notice' => $notice,
            'iNoType' => self::$enums['iNoType'],
            'check' => $checkStr,
            'dateTime' => date('Y年m月d日', time()),
            'depName' => $depName,
        ]);
    }

    /**
     * 保存公告
     * @return mixed
     * created by dale 2017/10/19
     */
    public function saveAfficheAction()
    {
        $this->view->disable();
        $iNoId = $this->request->getPost('iNoId', 'string');
        if ($iNoId) {
            UserPower::checkUserPower('Msg_AfficheList_Edit') or die('没有权限');
            $obj = XhmsgNotice::findFirst([
                'conditions' => 'bDelete=0 AND iNoId=:iNoId:',
                'bind' => ['iNoId' => $iNoId],
            ]);
        } else {
            UserPower::checkUserPower('Msg_AfficheList_Add') or die('没有权限');
            $obj = new XhmsgNotice();
            $obj->tTime = date('Y-m-d H:i:s', time());
        }
        $obj->assign($this->request->getPost());
        if ($obj->save()) {
            if ($iNoId) {
                return $this->sendSuccessResponse('编辑成功');
            } else {
                return $this->sendSuccessResponse('新增成功');
            }

        } else {
            return $this->sendSuccessResponse('新增失败');
        }
    }

    /**
     * 删除公告
     * created by dale 2017/10/18
     */
    public function delAfficheAction()
    {
        UserPower::checkUserPower('Msg_AfficheList_Del') or die('没有权限');
        $ids = $this->request->getPost('ids', 'string') or die('缺少参数');
        $ids = explode(',', $ids);
        $res = XhmsgNotice::deleteRecord('iNoId', $ids);
        if ($res) {
            return $this->sendSuccessResponse('删除成功');
        } else {
            return $this->sendSuccessResponse('删除失败');
        }
    }


    public function noAfListAction()
    {
        Assets::easyUI();

        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/msg/myTool.js');
        $this->view->pick('msg/noAfList');
        Assets::importJs('js/msg/noAfList.js');
        Template::exists('Msg_NoAf', 'list') or die(Main::showMessageModal('Msg_NoAf.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $listSearchArr = [];

        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 开始时间： ');
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' 结束时间： ');
        $enums = self::$enums;
        $enums['iNoType'][''] = '请选择';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_type',
            'data' => $enums['iNoType'], 'default' => '');

        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px');


        $this->view->setVars(array(
            'noAfList' => Template::createList('noAfList', 'Msg_NoAf', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
//                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ));
    }

    public function getNoAfListAction()
    {
        $this->view->disable();
        $key = $this->request->getPost('key', 'string');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime = $this->request->getPost('endTime', 'string');
        $type = $this->request->getPost('type', 'string');
        $builder = $this->modelsManager->createBuilder()
            ->columns("n.*")
            ->from(['n' => 'Admin\Models\msg\XhmsgNotice'])
            ->where('n.bDelete=0')->orderBy('n.tTime desc');
        $userId = Main::getLoginUserInfo('userId');
        if (!UserPower::checkUserPower('Msg_NoAfList_All')) {  //具有全部查看权限
            $builder->andWhere('( n.iNoType=1 AND sUserIds like :userId: ) 
             OR n.iNoType=2', array('userId' => '%,' . $userId . ',%'));
        }

        if ($key) {
            $builder->andWhere('n.sTitle like :key:', array('key' => '%' . $key . '%'));
        }
        if ($startTime & $endTime) {
            $builder->andWhere('DATE_FORMAT(n.tTime,\'%Y-%m-%d\') >= :startTime:  AND 
            DATE_FORMAT(n.tTime,\'%Y-%m-%d\') <= :endTime:', array('startTime' => $startTime, 'endTime' => $endTime));
        }

        if ($type) {
            $builder->andWhere('n.iNoType = :type: ', array('type' => $type));
        }

        $data = Main::runBuilderPaginator($builder, true);
        $enums = self::$enums;
        foreach ($data['rows'] as $index => $row) {
            $data['rows'][$index]['iNoType'] = $enums['iNoType'][$row['iNoType']];
        }
        Main::runUserNameById($data['rows'], ['iCreateUserId' => 'iCreateUserId',
            'iLastModifyUserId' => 'iLastModifyUserId'], true);
        return $this->sendJsonResponse($data);
    }


    public function getDepStaffAction()
    {
        return XhhrmStaff::getDepStaff(0);
    }

    public function testAction()
    {
        var_dump($_SERVER);
    }


}